package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.article.entity.ApCollection;
import com.usian.article.mapper.ApCollectionMapper;
import com.usian.article.service.IApCollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.model.behavior.dtos.CollectionBehaviorDto;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-10-15
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements IApCollectionService {

//    收藏行为
    @Override
    public void saveCollection(CollectionBehaviorDto dto) {
//        参数检验
        if (dto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        判断用户是否登录
        Boolean isUser = false;
        //从线程中获取用户信息
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId!=null){
            isUser=true;
        }
//        查看用户或者设备号对当前文章进行过收藏
        QueryWrapper<ApCollection> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(ApCollection::getArticleId,dto.getArticleId());
        if (isUser){
            //用户收藏行为
            queryWrapper.lambda().eq(ApCollection::getApUserId,userId);
        }else {
            //设备号收藏行为
            queryWrapper.lambda().eq(ApCollection::getEquipmentId,dto.getEquipmentId());
        }
        ApCollection apCollection = this.getOne(queryWrapper);
//        如果没有收藏记录/收藏行为
        if (apCollection==null){
            apCollection = new ApCollection();
            apCollection.setOperation(dto.getOperation());
            apCollection.setArticleId(dto.getArticleId());
            if (isUser){
                apCollection.setApUserId(userId);
            }else {
                apCollection.setEquipmentId(dto.getEquipmentId());
            }
            apCollection.setType(dto.getType());
            apCollection.setPublishedTime(dto.getPublishedTime());
            apCollection.setCollectionTime(new Date());
            boolean b = this.save(apCollection);
            if (!b){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存收藏行为失败");
            }
        }else {
//            如果收藏过，更新状态为取消，并记录修改的时间
            apCollection.setOperation(dto.getOperation());
            apCollection.setCollectionTime(new Date());
            boolean b = this.updateById(apCollection);
            if (!b){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"更新收藏行为失败");
            }
        }
    }
}
